package com.cbd.basic.leetcode.easy;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 两数之和
 */
@Slf4j
public class Solution1 {
    public static void main(String[] args) {
        int[] nums = {2,7,11,15};
        int target = 9;
        int[] result1 = twoSum1(nums, target);
        log.info("result1 = {}", result1);

        int[] result2 = twoSum2(nums, target);
        log.info("result2 = {}", result2);
    }

    /**
     * 时间复杂度：O(N²)，最坏情况下数组中任意两个数都要匹配一次
     * 空间复杂度：O(1)
     */
    public static int[] twoSum1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

    /**
     * 时间复杂度：O(N)
     * 空间复杂度：O(N)，哈希表的空间开销
     */
    public static int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[0];
    }
}
